<template>
	<el-dialog :title="form.postId ? $t('common.editBtn') : $t('common.addBtn')" width="800" v-model="visible" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="80px" v-loading="loading">
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="产品分类" prop="categoryId">
						<el-select v-model="form.categoryId" placeholder="请选择 产品分类" @change="handleCategoryChange" clearable>
							<el-option v-for="item in productTypeData" :key="item.id" :label="item.categoryName" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="产品名称" prop="productName">
						<el-input v-model="form.productName" placeholder="请输入 产品名称" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="产品型号" prop="model">
						<el-input v-model="form.model" placeholder="请输入 产品型号" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="产品品牌" prop="brand">
						<el-input v-model="form.brand" placeholder="请输入 产品品牌" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="产品频率" prop="frequency">
						<el-input v-model="form.frequency" placeholder="请输入 产品频率" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="产品选件" prop="accessories">
						<el-input v-model="form.accessories" placeholder="请输入 产品选件" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="产品图片" prop="images">
						<upload-img v-model:imageUrl="form.images" width="100px" height="100px">
							<template #empty>
								<el-icon class="add-icon"><Plus /></el-icon>
								<span>请上传产品图片</span>
							</template>
						</upload-img>
						<div class="add-card" @click="addCarouselItem">
							<el-icon class="add-icon"><Plus /></el-icon>
							<span class="add-text">添加轮播图</span>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="产品详情" prop="details">
						<editor v-model:get-html="form.details" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="systemPostDialog">
import { useMessage } from '/@/hooks/message';
import { getObj, addObj, putObj, validateExist } from '/@/api/qytest/sysProduct';
import { getProductCategory } from '/@/api/qytest/sysProductCategory';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import other from '/@/utils/other';
import { rule } from '/@/utils/validate';
import { get } from 'sortablejs';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

const { t } = useI18n();

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);

// 提交表单数据
const form = reactive({
	categoryName: '',
	id: '',
	productName: '',
	categoryId: '',
	model: '',
	brand: '',
	frequency: '',
	accessories: '',
	images: '',
	details: '',
	isNewProduct: '',
});
const productTypeData = ref([]);

// 定义校验规则
const dataRules = ref({
	productName: [{ required: true, message: '产品名称 不能为空', trigger: 'blur' }],
	categoryId: [{ required: true, message: '产品分类 不能为空', trigger: 'blur' }],
	model: [{ required: true, message: '产品型号 不能为空', trigger: 'blur' }],
	brand: [{ required: true, message: '产品品牌 不能为空', trigger: 'blur' }],
	images: [{ required: true, message: '产品图片 不能为空', trigger: 'change' }],
	details: [
		{
			validator: (rule: any, value: any, callback: any) => {
				callback(isEditorEmpty(value) ? '产品详情 不能为空' : undefined);
			},
			trigger: 'change',
		},
	],
});
const isEditorEmpty = (html: any) => {
	if (!html) return true;
	// 创建临时DOM元素解析HTML
	const tempDiv = document.createElement('div');
	tempDiv.innerHTML = html;
	// 检查是否存在有效内容
	const hasContent = tempDiv.textContent
		? tempDiv.textContent.trim() !== '' || // 文本内容
			tempDiv.querySelectorAll('img, video, iframe').length > 0
		: false; // 非文本内容
	return !hasContent;
};
const handleCategoryChange = (val: string) => {
	form.categoryName = other.findLabelByKey(productTypeData.value, 'id', val, 'categoryName');
};
// 打开弹窗
const openDialog = async (id: string, activeName: string) => {
	visible.value = true;
	form.id = '';

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});
	await getProductTypeData();

	// 获取sysProduct信息
	if (id) {
		form.id = id;
		await getSysProductData(id);
	} else {
		form.isNewProduct = activeName;
	}
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
const getProductTypeData = () => {
	getProductCategory({ current: -1 })
		.then((res: any) => {
			productTypeData.value = res.data.records || [];
		})
		.finally(() => {});
};
// 初始化表单数据
const getSysProductData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj({ id: id })
		.then((res: any) => {
			Object.assign(form, res.data[0]);
		})
		.finally(() => {
			loading.value = false;
		});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped>
.el-col {
	margin-bottom: 18px;
}
</style>
